package org.luxor.commons.zookeeper.lock;

import org.aopalliance.aop.Advice;
import org.luxor.commons.zookeeper.annotation.GlobalLock;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.annotation.AnnotationMatchingPointcut;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

/**
 * 分布式锁aop配置
 *
 * @author zengzh
 * @since 1.0.0
 */
public class ZkLockAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {

    /**
     * 切面
     */
    private final Advice advice;

    /**
     * 切入点
     */
    private final Pointcut pointcut;

    public ZkLockAdvisor(ZkLockInterceptor lockInterceptor) {
        this.advice = lockInterceptor;
        this.pointcut = buildPointcut();
    }

    @Override
    public Pointcut getPointcut() {
        return this.pointcut;
    }

    @Override
    public Advice getAdvice() {
        return this.advice;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        if (this.advice instanceof BeanFactoryAware) {
            ((BeanFactoryAware) this.advice).setBeanFactory(beanFactory);
        }
    }

    private Pointcut buildPointcut() {
        return AnnotationMatchingPointcut.forMethodAnnotation(GlobalLock.class);
    }

}